// Copyright (c) 2009 Hypirinha contributers
// This program is made available under the terms of the MIT License.
package org.hypirinha.html.codegen;

import static org.hypirinha.html.codegen.CodegenUtil.splitOntoMultipleLines;

import java.io.PrintStream;
import java.util.List;
import java.util.ArrayList;

public abstract class CompilationUnit {
    protected String packageName;
    protected String className;
    private List<String> imports = new ArrayList<String>();
    private List<Member> members = new ArrayList<Member>();
    public static String LICENCE = "// Copyright (c) 2009 Hypirinha contributers\n" +
            "// This program is made available under the terms of the MIT License.\n";

    public CompilationUnit(String packageName, String className) {
        this.className = className;
        this.packageName = packageName;
    }

    public String getClassName() {
        return className;
    }

    public String getFileName() {
        return packageName.replaceAll("\\.", "/") + "/" + className + ".java";
    }

    public void printTo(PrintStream printStream) {
        printStream.println(LICENCE + "package " + packageName + ";");
        printStream.println();
        printImports(printStream);
        printStream.println(splitOntoMultipleLines(startDeclaration()));
        for (Member member : getMembers()) {
            member.printTo(printStream);
        }
        printStream.println("}");
    }

    protected void printImports(PrintStream printStream) {
        if (imports.size() > 0) {
            for (String importedPattern : imports) {
                printStream.println("import " + importedPattern + ";");
            }
            printStream.println();
        }
    }

    public List<Member> getMembers() {
        return members;
    }

    public void addImport(String importedPattern) {
        imports.add(importedPattern);
    }

    protected abstract String startDeclaration();
}
